package fr.cdj.thebox.client.utils;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.HasValue;
import com.google.inject.Inject;

import fr.cdj.thebox.client.resources.TheboxBundle;

public class Checkbox extends Icon implements HasValue<Boolean> {

	private boolean checked;
	private boolean valueChangeHandlerInitialized;

	@Inject
	public Checkbox(TheboxBundle resources) {
		super(resources);
		this.addStyleName(resources.getStyle().checkbox());
		checked = false;

		this.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent arg0) {
				Checkbox.this.setValue(!checked);
			}
		});
	}

	@Override
	public Boolean getValue() {
		return checked;
	}

	@Override
	public void setValue(Boolean value) {
		checked = value;
		if (value) {
			this.getElement().setAttribute("checked", "");
		} else {
			this.getElement().removeAttribute("checked");
		}
	}

	@Override
	public HandlerRegistration addValueChangeHandler(ValueChangeHandler<Boolean> handler) {
		if (!valueChangeHandlerInitialized) {
			ensureDomEventHandlers();
			valueChangeHandlerInitialized = true;
		}
		return addHandler(handler, ValueChangeEvent.getType());
	}

	protected void ensureDomEventHandlers() {
		addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				ValueChangeEvent.fire(Checkbox.this, getValue());
			}
		});
	}

	@Override
	public void setValue(Boolean value, boolean fireEvents) {
		setValue(value);
		if (fireEvents) {
			ValueChangeEvent.fire(this, value);
		}
	}

}